package com.v1.video.service;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;

import com.v1.video.AppContext;
import com.v1.video.statistics.CustomerStatistics;
import com.v1.video.util.Logger;


/**
 * 发送in和end统计的后台服务
 * Created by jieyaozu on 2016/12/22.
 */
public class StatisticsInEndService extends Service {

    private AppContext app;
    private boolean isBind = true;
    private final int ENTERAPP = 0;
    /**
     * 上一次检测时应用是否处于栈顶
     */
    private boolean isPreAppTop = false;

    @Override
    public void onCreate() {
        super.onCreate();
        isPreAppTop = true;
        app = AppContext.getInstance();
        CustomerStatistics.enterApp(app);
        startListenerThread();
    }

    private void startListenerThread() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (isBind) {
                    //应用是否处于栈顶
                    boolean flag = app.isTopApplication();
                    app.isForeground = flag;
                    if (flag != isPreAppTop) {
                        if (flag) {
                        	 mHandler.sendEmptyMessage(ENTERAPP);
                        } else {
                            CustomerStatistics.exitApp();
                        }
                    }

                    isPreAppTop = flag;
                    try {
                        Thread.sleep(500);
                    } catch (Exception e) {
                        Logger.e("StatisticsInEndService", e.toString());
                    }
                }
            }
        }).start();
    }


    @Override
    public IBinder onBind(Intent intent) {
        Logger.d("StatisticsInEndService", "service is bind");
        isBind = true;
        return null;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Logger.d("StatisticsInEndService", "service is unbind");
        isBind = false;
        return super.onUnbind(intent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        CustomerStatistics.exitApp();
    }
    
    @SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case ENTERAPP:
                    CustomerStatistics.enterApp(app);
                    break;
            }
        }
    };
}
